package com.randi.system.service;

import com.randi.common.enums.excel.ExportStatus;
import com.randi.common.utils.RedisUtil;
import com.randi.common.utils.StringUtils;
import com.randi.common.utils.excel.ExcelUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author ziye
 */
@Component
@Slf4j
public class ThreadExportService<T> {

    private static final Logger logger = LoggerFactory.getLogger("com.randi.framework.service.ThreadExportService");

    @Resource
    private RedisUtil redisUtil;

    private void printLog(ExportStatus status, String taskId) {
        logger.info("------------------------------- 多线程任务 -------------------------------");
        logger.info("任务名称：{}", "导出数据");
        logger.info("任务编号：{}", taskId);
        logger.info("导出状态：{}", status);
        logger.info("------------------------------------------------------------------------");
    }

    public ExportStatus getExportStatus(String taskId) {
        String status = redisUtil.getCache(taskId);
        if(StringUtils.isEmpty(status)){
            return ExportStatus.NOT_EXIST;
        }

        return ExportStatus.valueOf(status);
    }

    /**
     * 创建导出数据任务
     */
    @Async("TaskExecutor")
    public void createDefaultExport(Class<T> clazz, List<T> list, String taskId) {
        try {
            redisUtil.setCache(taskId, ExportStatus.LOADING);
            printLog(ExportStatus.LOADING, taskId);
            ExcelUtil<T> excelUtil = new ExcelUtil<>(clazz);
            excelUtil.init(list);
            excelUtil.exportExcel(taskId);
            TimeUnit.SECONDS.sleep(5);
            printLog(ExportStatus.SUCCESS, taskId);
            redisUtil.setCache(taskId, ExportStatus.SUCCESS, 2, TimeUnit.HOURS);
        } catch (Exception e) {
            e.printStackTrace();
            printLog(ExportStatus.FAIL, taskId);
            redisUtil.setCache(taskId, ExportStatus.FAIL, 2, TimeUnit.HOURS);
        }
    }
}
